#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
用户权限相关操作
"""

from __future__ import with_statement

from django.http import HttpResponseRedirect, HttpResponseServerError
from django.core.urlresolvers import reverse
from jiaju.common import md5mgr
from jiaju.common import log_execption
from jiaju.common import exception_mgr
from jiaju.common import cache

from jiaju.model import User, Privilege
from jiaju.common.constants.constant import Constant

SESSION_KEY = Constant.SESSION_KEY
SESSION_EXPIRE_TIME = 60 * 60 * 24

def login(request,username, password):
    """
     根据用户名和密码判断是否是合法用户
    @param username: 登录账号
    @param password: 登录密码
    @return:  0, session_id or -1, fail message
    """
    
    LOGIN_ERROR = "您输入的用户名或者密码不正确，请重新登录。"
    LOGIN_ERROR_SESSION = "您输入的验证码不正确";
    LOGIN_NOT_USER = "您输入的用户不存在"
    
    checkcode_key = request.COOKIES.get("checkcode", None)
    if checkcode_key == None : 
        return -1 , LOGIN_ERROR_SESSION
    
    checkcode_fromcache = cache.get(checkcode_key)
    checkcode_fromuser = request.REQUEST.get("checkcode")
    
    if checkcode_fromcache != checkcode_fromuser:
        return -1,LOGIN_ERROR_SESSION
    
    if not username or not password:
        return -1, LOGIN_ERROR
    session_id = get_session_id(username, password)
    user_info = None
    password = md5mgr.mkmd5fromstr(password)
    
    if not user_info:
        users = User.load(username=username)
        if users == None:
            return -1,LOGIN_NOT_USER
        if not users or users.password != password: 
            print "login passwd %s , user passwd %s"%(password,users.password) 
            return -1 , LOGIN_ERROR
    return 0, session_id


def logout(request):
    response = HttpResponseRedirect('/admin/login/')
    response.set_cookie(SESSION_KEY,None)
    return response

def get_userinfo(request):
    session_id = request.COOKIES.get(SESSION_KEY, None)
    print "session_id%s:"%session_id
    if session_id is not None:
        user = User.load(session_id=session_id)
        if user is not None:
            return user
    return None


def get_privilege(request, page_id=0):
    """根据当前登录用户信息和功能编号，获取对该功能的权限
    @param request: 用户请求
    @param page_id: 页面编号
    @return: privilege
    """
    privilege = None
    
    user = get_userinfo(request)
    if user is None:
        return privilege
    
    privilege = Privilege.load(user_id=user.id, page_id=page_id)
    return privilege
    
    

def get_user_list(page, pagesize, uid=None):
    """获取用户列表"""
    where = " 1 = 1 "
    if uid:
        where = " uid=%s" % uid
    total = User.count(where)
    infos = []
    if total:
        infos = User.query(condition=where)
    return total, infos
        
def add_user(user_info):
    """添加用户"""
    user = User()
    id = int(user_info.get("id", 0))
    password = user_info.get("password")
    session_id = get_session_id(user_info["username"], password)
    if id:
        user = User.load(id=user_info["id"])
        if password and password != user.password:
            user.password = md5mgr.mkmd5fromstr(password)
            user.session_id = session_id
    else:
        user = User()
        user.username = user_info["username"]
        user.password = md5mgr.mkmd5fromstr(password)
        if password and password != user.password:
            user.session_id = session_id
    
    user.username = user_info.get("username")
    if user_info.get("nickname"):
        user.nickname = user_info.get("nickname")
    if user_info.get("remark"):
        user.remark = user_info.get("remark")
         
    return user.persist()

def get_session_id(username , password):
    """获取SESSION_ID"""
    if username == None or password == None : 
        raise "username is %s , password is %s " % (username, password)
    print "username is %s , password is %s " % (username, password)
    print md5mgr.mkmd5fromstr('%s%s' % (username, password))
    return md5mgr.mkmd5fromstr('%s%s' % (username, password))


def del_user(id):
    """删除用户"""
    if id :
        user = User()
        user.id = id
        user.delete()
    else:
        raise "id is null"
    
if __name__ == '__main__':
    print get_session_id('mazheng', '123')
